package com.texaco.chapasFutbol.scene;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.andengine.engine.camera.Camera;
import org.andengine.entity.IEntity;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.AutoWrap;
import org.andengine.entity.text.Text;
import org.andengine.entity.text.TextOptions;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.IFont;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.util.HorizontalAlign;
import org.andengine.util.color.Color;
import org.andengine.util.progress.IProgressListener;

import android.content.res.Resources;

import com.texaco.chapasFutbol.ChapasFutbolActivity;
import com.texaco.chapasFutbol.R;
import com.texaco.chapasFutbol.buttons.Button;
import com.texaco.chapasFutbol.buttons.IButtonCallBack;
import com.texaco.chapasFutbol.entidades.Game;
import com.texaco.chapasFutbol.resources.Resource;

/**
 * Clase que implementará el tutorial
 * @author texaco
 *
 */
public class TutorialScene extends SceneBase{

	List<IEntity> images;
	List<String> texts;
	Rectangle bg;
	Sprite panel;
	Text tTutorial;
	Button bNext;
	Button bBefore;
	int pos;
	
	public TutorialScene(Game game){
		super(game);
		this.setBackground(new Background(Color.BLACK));
	}
	
	/**
	 * Muestra el tutorial.
	 */
	public void showTutorial(){
		this.attachChild(MenuPrincipalScene.LAYER_TUTORIAL, bg);
		pos = 0;
		panel.attachChild(images.get(pos));
		tTutorial.setText(texts.get(pos));
	}
	
	/**
	 * Oculta el tutorial.
	 */
	public void hiddeTutoria(){
		game.getActivity().getEngine().getEngineLock().lock();
		this.getChildByIndex(MenuPrincipalScene.LAYER_TUTORIAL).detachChild(bg);
		panel.detachChild(images.get(pos));
		game.getActivity().getEngine().getEngineLock().unlock();
		this.back();
	}

	/**
	 * Devuelve el texto obtenido de los recursos.
	 * @return
	 */
	private List<String> loadTexts() {
		Resources res = game.getActivity().getResources();
		String[] textArray = res.getStringArray(R.array.a_tutorial_text);
		List<String> result = new ArrayList<String>();
		for(int i = 0; i < textArray.length; i++){
			result.add(textArray[i]);
		}
		return result;
	}

	/**
	 * Devuelve un listado con las imagenes cargadas.
	 * @param panel 
	 * @return
	 */
	private List<IEntity> loadImages(Sprite panel) {
		Map<String, Resource> res = com.texaco.chapasFutbol.resources.Resources.graphicResources.get(
				com.texaco.chapasFutbol.resources.Resources.ATLAS_TUTORIAL).getResources();
		
		List<IEntity> result = new ArrayList<IEntity>();
		ChapasFutbolActivity activity = game.getActivity();
		Map<String, ITextureRegion> shapeMap = activity.getShapesMaps();
		Resources actRes = activity.getResources();
		
		/*
		 * Obtenemos el ancho de las imagenes.
		 */
		int widthImgs = res.get(com.texaco.chapasFutbol.resources.Resources.SHAPE_TUTORIAL_1).getWidth();
		
		float x = panel.getWidth()/2f - (float)widthImgs/2f;
		float y = actRes.getInteger(R.integer.layout_tutorial_top_margin);
		
		for(Entry<String, Resource> entry : res.entrySet()){
			result.add(new Sprite(x, y, shapeMap.get(entry.getKey()), activity.getVertexBufferObjectManager()));
		}
		return result;
	}

	private void next() {
		/*
		 * Aquí podríamos poner alguna transición entre las imágenes
		 */
		if(pos == images.size() - 1){
			//El ultimo caso - Cerramos el tuto
			hiddeTutoria();
		}else{
			game.getActivity().getEngine().getEngineLock().lock();
			panel.detachChild(images.get(pos));
			game.getActivity().getEngine().getEngineLock().unlock();
			panel.attachChild(images.get(++pos));
			tTutorial.setText(texts.get(pos));
		}
	}

	private void before() {
		/*
		 * Aquí podríamos poner alguna transición entre las imágenes
		 */
		if(pos != 0){
			game.getActivity().getEngine().getEngineLock().lock();
			panel.detachChild(images.get(pos));
			game.getActivity().getEngine().getEngineLock().unlock();
			panel.attachChild(images.get(--pos));
			tTutorial.setText(texts.get(pos));
		}
	}

	@Override
	protected void initAsync(IProgressListener pProgressListener) {
		ChapasFutbolActivity activity = game.getActivity();
		Resources res = activity.getResources();
		Camera cam = activity.getEngine().getCamera();
		
		bg = new Rectangle(0, 0, 
				cam.getWidth(), cam.getHeight(), 
				activity.getVertexBufferObjectManager());
		bg.setColor(0, 0, 0, 1);
		this.setBackgroundEnabled(true);
		
		ITextureRegion panelTexture = activity.getShapesMaps().get(com.texaco.chapasFutbol.resources.Resources.SHAPE_TUTORIAL_PANEL);
		float panelX = (bg.getWidth() - panelTexture.getWidth())/2f;
		float panelY = (bg.getHeight() - panelTexture.getHeight())/2f;//FIXME: LO COLOCO CENTRADO PERO DEBE DE ESTAR UN POCO DESPLAZADO HACIA ARRIBA.
		panel = new Sprite(panelX, panelY, panelTexture, activity.getVertexBufferObjectManager());
		
		bg.attachChild(panel);

		images = loadImages(panel);
		texts = loadTexts();
		
		float leftMargin = res.getInteger(R.integer.layout_left_margin);
		float topMargin = res.getInteger(R.integer.layout_top_margin);
		float bottomMargin = res.getInteger(R.integer.layout_bottom_margin);
		float rightMargin = res.getInteger(R.integer.layout_right_margin);
		Font buttonFont = activity.getFontMap().get(com.texaco.chapasFutbol.resources.Resources.FONT_TUTORIAL);
		String buttonShape = Game.BOTON_ANTERIOR_SHAPE;
		bNext = new Button(game, this, panel, 
				0, 
				0, 
				R.string.tLabelButtonNext, 
				buttonFont, buttonShape, 
				new IButtonCallBack() {
			
			public String fire() {
				next();
				return null;
			}

		});
		bNext.setPosition(panel.getWidth() - leftMargin - bNext.getWidth(), 
				panel.getHeight() - bottomMargin - bNext.getHeight());
		
		bBefore = new Button(game, this, panel, 
				0, 
				0, 
				R.string.tLabelButtonBefore, 
				buttonFont, buttonShape, 
				new IButtonCallBack() {
			
			public String fire() {
				before();
				return null;
			}

		});
		bBefore.setPosition(rightMargin, panel.getHeight() - bottomMargin - bBefore.getHeight());
		
		IFont textFont = buttonFont;
		float tTextX = bNext.getWidth() + leftMargin * 2;
		float tTextY = panel.getHeight()/2;
		CharSequence firstText = texts.get(0);
		int tTutMaxChar = 300;
		float tTutWith = (panel.getWidth()/2 - tTextX)*2f;
		TextOptions tTutOpts = new TextOptions(AutoWrap.WORDS, tTutWith, HorizontalAlign.CENTER, 0);
		tTutorial = new Text(tTextX, tTextY, 
				textFont, firstText, 
				tTutMaxChar, tTutOpts, 
				activity.getVertexBufferObjectManager());
		panel.attachChild(tTutorial);
		
		pos = 0;		
	}

	@Override
	protected void update() {
		// TODO Auto-generated method stub
		
	}
	
	protected int layerCount(){
		return 2;
	}

	@Override
	protected boolean async() {
		return true;
	}
}
